<template>
  <div>
    <el-button
      type="danger"
      @click="showEditForm('add')"
      v-if="userInfo.roleType === 1"
      >新增分类</el-button
    >
    <Table
      :columns="columns"
      :showPagination="false"
      :dataSource="tableData"
      :fetch="loadDataList"
      :options="tableOptions"
    >
      <template #cover="{ index, row }">
        <Cover :cover="row.cover"></Cover>
      </template>
      <template #op="{ index, row }" v-if="userInfo.roleType === 1">
        <div class="op">
          <a
            href="javascript:void(0)"
            class="a-link"
            @click="showEditForm('update', row)"
            >修改</a
          >
          <el-divider direction="vertical" />
          <a href="javascript:void(0)" class="a-link" @click="delCategory(row)"
            >删除</a
          >
          <el-divider direction="vertical" />
          <a
            href="javascript:void(0)"
            :class="[index == 0 ? 'not-allowed' : 'a-link']"
            @click="changeSort(index, 'up')"
            >上移</a
          >
          <el-divider direction="vertical" />
          <a
            href="javascript:void(0)"
            :class="[
              index == tableData.list.length - 1 ? 'not-allowed' : 'a-link',
            ]"
            @click="changeSort(index, 'down')"
            >下移</a
          >
        </div>
      </template>
    </Table>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      @close="dialogConfig.show = false"
      ><el-form :model="formData" :rules="rules" ref="formDataRef">
        <el-form-item prop="categoryName" label="名称 ">
          <el-input
            placeholder="请输入分类名称"
            v-model.trim="formData.categoryName"
            size="large"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="cover" label="封面 ">
          <CoverUpload v-model="formData.cover"></CoverUpload>
        </el-form-item>
        <el-form-item prop="categoryDesc" label="简介 ">
          <el-input
            placeholder="请输入分类介绍"
            v-model.trim="formData.categoryDesc"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4 }"
            size="large"
          >
          </el-input>
        </el-form-item> </el-form
    ></Dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import md5 from "js-md5";

const { proxy } = getCurrentInstance();
const userInfo = ref(proxy.VueCookies.get("userInfo"));
const api = {
  loadDataList: "/category/loadAllCategory4Blog",
  saveCategory: "category/saveCategory4Blog",
  delCategory: "/category/delCategory4Blog",
  changeSort: "/category/changeCategorySort4Blog",
};
const columns = [
  {
    label: "封面",
    prop: "cover",
    width: 80,
    scopedSlots: "cover",
  },
  {
    label: "名称",
    prop: "categoryName",
    width: 200,
  },
  {
    label: "简介",
    prop: "categoryDesc",
  },
  {
    label: "博客数量",
    prop: "blogCount",
    width: 80,
  },
  {
    label: "操作",
    prop: "op",
    width: 200,
    scopedSlots: "op",
  },
];

const tableData = reactive({});
const tableOptions = { extHeight: 10 };
const loadDataList = async () => {
  let result = await proxy.Request({
    url: api.loadDataList,
  });
  if (!result) {
    return;
  }
  console.log(result.data);
  tableData.list = result.data;
};
const dialogConfig = reactive({
  show: false,
  title: "标题",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

// 分类表单填写
const formData = reactive({});
const rules = {};
const formDataRef = ref();
//新增、编辑分类
const showEditForm = (type, data) => {
  dialogConfig.show = true;
  nextTick(() => {
    formDataRef.value.resetFields();

    if (type == "add") {
      dialogConfig.title = "新增分类";
    } else if (type == "update") {
      dialogConfig.title = "编辑分类";
      Object.assign(formData, data);
      console.log(data);
      // console.log(formData);
    }
  });
};
const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData);
    let result = await proxy.Request({
      url: api.saveCategory,
      params,
    });
    if (!result) {
      return;
    }
    dialogConfig.show = false;
    Object.keys(formData).forEach((key) => {
      formData[key] = "";
    });
    console.log(formData);
    ElMessage.success("保存成功");
    loadDataList();
  });
};

const delCategory = (data) => {
  proxy.Confirm(`你去定要删除${data.categoryName}`, async () => {
    let result = await proxy.Request({
      url: api.delCategory,
      params: {
        categoryId: data.categoryId,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
    ElMessage.success("删除成功");
  });
};

// 上移，下移
const changeSort = async (index, type) => {
  let categoryList = tableData.list;
  if (
    (type === "down" && index === categoryList.length - 1) ||
    (type === "up" && index === 0)
  ) {
    return;
  }
  let number = type == "down" ? 1 : -1;
  let temp = categoryList[index];
  categoryList.splice(index, 1);
  categoryList.splice(index + number, 0, temp);
  let result = await proxy.Request({
    url: api.changeSort,
    dataType: "json",
    params: categoryList,
  });
  if (!result) {
    return;
  }
  ElMessage.success("更新成功！");
};
</script>

<style lang="scss" scoped></style>
